import Taro from '@tarojs/taro'

/**
 * WebSocket 配置工具类
 * 用于处理不同环境下的 WebSocket 连接配置
 */
export class WebSocketConfig {
  private static instance: WebSocketConfig
  
  private constructor() {}
  
  static getInstance(): WebSocketConfig {
    if (!WebSocketConfig.instance) {
      WebSocketConfig.instance = new WebSocketConfig()
    }
    return WebSocketConfig.instance
  }

  /**
   * 获取 WebSocket URL
   * 根据当前协议和环境自动选择正确的协议和端口
   */
  getWebSocketUrl(token: string): string {
    if (!token) {
      throw new Error("用户未登录，无法建立 WebSocket 连接")
    }

    // 获取当前协议
    const isHttps = this.isHttps()
    const protocol = isHttps ? 'wss:' : 'ws:'
    
    // 根据环境配置不同的主机和端口
    const config = this.getEnvironmentConfig()
    
    return `${protocol}//${config.host}:${config.port}/chat/${token}`
  }

  /**
   * 判断当前是否为 HTTPS 环境
   */
  private isHttps(): boolean {
    // 检查多种环境
    if (typeof window !== 'undefined') {
      return window.location.protocol === 'https:'
    }
    
    // 小程序环境或其他环境
    const systemInfo = Taro.getSystemInfoSync()
    return systemInfo.platform === 'weapp' || process.env.NODE_ENV === 'production'
  }

  /**
   * 根据环境获取配置
   */
  private getEnvironmentConfig() {
    const isDev = process.env.NODE_ENV === 'development'
    const isHttps = this.isHttps()
    
    if (isDev) {
      // 开发环境配置
      return {
        host: 'localhost',
        port: isHttps ? '443' : '8088'
      }
    } else {
      // 生产环境配置
      return {
        host: 'www.api.nl9555.com',
        port: isHttps ? '443' : '8088'
      }
    }
  }

  /**
   * 获取备用 WebSocket URL（用于重连）
   */
  getBackupWebSocketUrl(token: string): string {
    if (!token) {
      throw new Error("用户未登录，无法建立 WebSocket 连接")
    }

    const isHttps = this.isHttps()
    const protocol = isHttps ? 'wss:' : 'ws:'
    
    // 备用服务器配置
    const backupConfig = {
      host: 'api2.nl9555.com', // 备用服务器
      port: isHttps ? '443' : '8088'
    }
    
    return `${protocol}//${backupConfig.host}:${backupConfig.port}/chat/${token}`
  }

  /**
   * 检查 WebSocket 连接是否可用
   */
  async checkConnection(url: string): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        const testWs = new WebSocket(url)
        
        const timeout = setTimeout(() => {
          testWs.close()
          resolve(false)
        }, 5000) // 5秒超时
        
        testWs.onopen = () => {
          clearTimeout(timeout)
          testWs.close()
          resolve(true)
        }
        
        testWs.onerror = () => {
          clearTimeout(timeout)
          resolve(false)
        }
        
      } catch (error) {
        console.error('WebSocket 连接检查失败:', error)
        resolve(false)
      }
    })
  }

  /**
   * 获取连接状态信息
   */
  getConnectionInfo() {
    const isHttps = this.isHttps()
    const config = this.getEnvironmentConfig()
    
    return {
      protocol: isHttps ? 'wss' : 'ws',
      host: config.host,
      port: config.port,
      isSecure: isHttps,
      environment: process.env.NODE_ENV
    }
  }
}

// 导出单例实例
export const websocketConfig = WebSocketConfig.getInstance()

/**
 * 便捷函数：获取 WebSocket URL
 */
export const getWebSocketUrl = (token: string): string => {
  return websocketConfig.getWebSocketUrl(token)
}

/**
 * 便捷函数：获取备用 WebSocket URL
 */
export const getBackupWebSocketUrl = (token: string): string => {
  return websocketConfig.getBackupWebSocketUrl(token)
}

/**
 * 便捷函数：检查连接可用性
 */
export const checkWebSocketConnection = (url: string): Promise<boolean> => {
  return websocketConfig.checkConnection(url)
}
